#include "event_loop_thread_pool.h"
#include "event_loop.h"
#include "event_loop_thread.h"

EventLoopThreadPool::EventLoopThreadPool(EventLoop& baseLoop, int numThreads)
    : baseLoop_(baseLoop), numThreads_(numThreads) {}

EventLoopThreadPool::~EventLoopThreadPool() = default;

void EventLoopThreadPool::start() {
    if (started_) return;
    started_ = true;

    for (int i = 0; i < numThreads_; ++i) {
        auto thread = std::make_unique<EventLoopThread>();
        EventLoop& loop = thread->startLoop();
        threads_.push_back(std::move(thread));
        loops_.push_back(&loop);
    }
}

EventLoop& EventLoopThreadPool::getNextLoop() {
    if (loops_.empty()) {
        return baseLoop_;  // 若未开启多线程，则回退到主 Loop
    }
    EventLoop& loop = *loops_[next_];
    next_ = (next_ + 1) % loops_.size();
    return loop;
}